
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class ImageUtil {

    public static class ImageConversionException extends Exception {
        public ImageConversionException(String message) {
            super(message);
        }
    }

    private ImageUtil() {
        // Prevent instantiation
    }

    public static String imageToBase64(RenderedImage img, String formatName) throws ImageUtil.ImageConversionException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try {
            ImageIO.write(img, formatName, os);
            return Base64.getEncoder().encodeToString(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
            throw new ImageConversionException("转换图片至Base64编码失败");
        }
    }

    public static BufferedImage base64ToImage(String base64) throws ImageUtil.ImageConversionException {
        try {
            return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64)));
        } catch (IOException e) {
            e.printStackTrace();
            throw new ImageConversionException("转换Base64编码至图片失败");
        }
    }
}
